#!/usr/bin/env python

import sys, os, urllib2
import random

from BeautifulSoup import BeautifulSoup   

FREQUENCYPAGE="http://www.walottery.com/WinningNumbers/FrequencyOfNumbersDrawn/FrequencyOfNumbersDrawn.aspx?game=Hit5"
PURCHASES=10

winningNumbers = [14, 18, 19, 28, 36]
winningNumbers = [4, 5, 29, 37, 38]
winningNumbers = [01,04,16,22,28]

webpage = urllib2.urlopen(FREQUENCYPAGE)
response = webpage.read()

found = False
text_to_parse = []
for line in response.split("\n"):
   if line.find("<!-- RIGHT TABLE -->") > -1:
     found = True
     #print "Found <!-- RIGHT TABLE -->"
   
   if found:
     text_to_parse.append(line) 

soup = BeautifulSoup(''.join(text_to_parse))

table = soup.find('table')
rows = table.findAll('tr')

frequencies = []
for tr in rows:
  cols = tr.findAll('td')
  items = []
  for td in cols:
      try:
        cell = int(td.find(text=True))
        items.append(cell)
      except ValueError, e:
        continue
  if len(items) != 0:
    frequencies.append((items[0], items[1]))
#print frequencies
#for ball in frequencies:
#   print "Ball", ball[0], "has frequency of", ball[1]

ballcollection = []

for ball, frequency in frequencies:
  if frequency > 78 and frequency < 95:
     frequency *= 1.3
     frequency = int(frequency)
  for i in range(0, frequency):
    ballcollection.append(ball)


winningmatches = [0,0,0,0,0]

for i in range(0,PURCHASES):
  myNumbers = []
  try: 
    while len(myNumbers) < 5:
      index = random.randint(0,len(ballcollection)-1)
      pick = ballcollection[index]
      if pick not in myNumbers:
        myNumbers.append(pick)
  except IndexError, e:
    print index, "out of", len(ballcollection)
   
  myNumbers.sort()
  print myNumbers
  matches = len( list(set(myNumbers) & set(winningNumbers)) ) 

  if matches > 1:
    #print "Found", matches, "matches in ticket:",  myNumbers
    winningmatches[matches-1] += 1
    
  if myNumbers == winningNumbers:
    print "Found the winning ticket in", i, "tries"
    break

print winningmatches
odds = float(sum(winningmatches)) / i
print odds
#print myNumbers
